<template>
  <div class="productManager">
    <div class="breadcrumb">
      <el-icon>
        <Location />
      </el-icon>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="content">
      <div class="top">
        <div style="display:flex;">
          <el-input v-model="account" placeholder="请输入账户" :prefix-icon="Search"></el-input>
          <el-select v-model="department" placeholder="请选择部门" clearable="">
            <el-option :label="item.name" :value="item.name" v-for="item in departmentList" :key="item.id" />

          </el-select>
          <el-button type="primary" @click="togetUser()">确认</el-button>
        </div>
        <div>
          <!-- <el-button type="primary" @click="dialogVisible = true;">添加产品管理员</el-button> -->
          <el-radio-group v-model="type" @change="changeType">
            <el-radio-button :label="null">全部用户</el-radio-button>
            <el-radio-button :label="1">冻结用户</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column prop="account" label="账户">
          <template #default="scope">
            <div
              style="color:blue;cursor:pointer;"
              @click="showInfo(scope.row)"
            >{{ scope.row.account}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="sex" label="性别" />
        <el-table-column prop="identity" label="身份" />
        <el-table-column prop="department" label="部门" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="状态" width="140">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status ==0">正常</el-tag>
            <el-tag type="info" v-else>冻结</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" />
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              :disabled="scope.row.status ==1"
              @click="toggleType(scope.$index, scope.row)"
            >冻结</el-button>
            <el-button
              size="small"
              type="success"
              :disabled="scope.row.status ==0"
              @click="toggleType(scope.$index, scope.row)"
            >解结</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog draggable
      v-model="dialogVisible"
      title="新建产品管理员"
      width="30%"
      @close="dialogVisibleClose(ruleFormRef)"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="账户" prop="account">
          <el-input v-model="ruleForm.account" placeholder="账户" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" placeholder="密码" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="ruleForm.sex" placeholder="性别" style="width:100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="email" prop="email">
          <el-input v-model="ruleForm.email" placeholder="email" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="ruleForm.department" placeholder="部门" style="width:100%">
            <el-option :label="item.name" :value="item.name" v-for="item in departmentList" :key="item.id" />

          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog draggable v-model="infoDialogVisible" title="用户信息" width="30%">
      <el-row :gutter="20">
        <el-col :span="10" style="text-align: center">
          <el-avatar :size="100" :src="'http://127.0.0.1:7001' + info.imageUrl" />
        </el-col>
        <el-col :span="14">
          <el-descriptions :column="1">
            <el-descriptions-item label="账户">{{info.account}}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{info.name}}</el-descriptions-item>
            <el-descriptions-item label="性别">{{info.sex}}</el-descriptions-item>
            <el-descriptions-item label="部门">{{info.department}}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{info.email}}</el-descriptions-item>
            <el-descriptions-item label="状态">{{info.status == 1 ? '冻结' : '正常'}}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <div style="text-align: right;">
        <el-button type="primary" link @click="toDeit()">编辑</el-button>
        <el-button type="primary" link @click="empowermentDialogVisible = true">赋权</el-button>
        <el-button type="danger" link @click="deleteUser(info)">删除用户</el-button>
      </div>
    </el-dialog>

    <el-dialog draggable v-model="empowermentDialogVisible" title="赋权" width="30%">
      <el-radio-group v-model="identity">
        <el-radio label="产品管理员">产品管理员</el-radio>
        <el-radio label="用户管理员">用户管理员</el-radio>
        <el-radio label="消息管理员">消息管理员</el-radio>
      </el-radio-group>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="empowermentDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="empowermentOK()">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog draggable v-model="userDialogVisible" title="修改用户" width="30%">
      <el-form
        ref="ruleUserRef"
        :model="ruleUser"
        :rules="userRules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="账户" prop="account">
          <el-input v-model="ruleUser.account" :disabled="isEdit" placeholder="账户" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleUser.name" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="ruleUser.sex" placeholder="性别" style="width:100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="email" prop="email">
          <el-input v-model="ruleUser.email" placeholder="email" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="ruleUser.department" placeholder="部门" style="width:100%">
            <el-option :label="item.name" :value="item.name" v-for="item in departmentList" :key="item.id" />

          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="userSubmitForm(ruleUserRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addProductManager,
  getUser,
  deletUser,
  userChangeType,
  empowerment,
  modifyProductManager,
  getDepartment
} from "@/api/user";
import {
  addOperationLog
} from "@/api/log";

import { useRouter } from "vue-router";
const router = useRouter();

// 调用store树中内容需要引入
import { useStore } from "vuex";
// 获取store
const store = useStore();

import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  House,
  Message,
  Grid,
  Avatar,
  Position,
  ChatLineSquare,
  Notebook,
  UserFilled,
  User,
  Notification,
  ChatRound,
  Search
} from "@element-plus/icons-vue";
const tableData = ref([]);
const handleEdit = (index, row) => {
  console.log(index, row);
};
const handleDelete = (index, row) => {
  console.log(index, row);
  ElMessageBox.confirm(
    "是否去掉此用户的管理员职位? 删除后此用户将重新展现在用户列表中",
    "删除操作",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(() => {})
    .catch(() => {});
};

const dialogVisible = ref(false);
const ruleFormRef = ref();
const ruleForm = reactive({
  account: "",
  password: "",
  name: "",
  sex: "",
  email: "",
  department: ""
});

const rules = reactive({
  account: [{ required: true, message: "账户", trigger: "blur" }],
  password: [{ required: true, message: "账户", trigger: "blur" }],
  name: [{ required: true, message: "账户", trigger: "blur" }],
  sex: [{ required: true, message: "账户", trigger: "blur" }],
  email: [{ required: true, message: "账户", trigger: "blur" }],
  department: [{ required: true, message: "账户", trigger: "blur" }]
});

const submitForm = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addProductManager(ruleForm).then(res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        togetUser();
        ElMessage.success(res.data.message);
        dialogVisible.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const dialogVisibleClose = formEl => {
  if (!formEl) return;
  formEl.resetFields();
};
const account = ref();
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref();
const department = ref(null);
const togetUser = () => {
  let query = {
    type: type.value,
    account: account.value,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    department:department.value
  };
  getUser(query).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    // ElMessage.success(res.data.message);
    tableData.value = res.data.data.list;
    total.value = res.data.data.total;
  });
};


const type = ref(null);
const changeType = e => {
  // console.log(e)
  togetUser(e);
};

const toggleType = (index, row) => {
  ElMessageBox.confirm(
    "确定" + (row.status == 1 ? "解冻" : "冻结") + "此用户",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(() => {
      let data = {
        type: row.status == 1 ? 0 : 1,
        id: row.id
      };
      userChangeType(data).then(async res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        await addOperationLog({operation_person:localStorage.getItem("name"),operation_content:"对id是" + row.id + '的用户' + (row.status == 1 ? "解冻" : "冻结"),operation_level:"高级"});

        togetUser();
        ElMessage.success(res.data.message);
      });
    })
    .catch(() => {});
};

const infoDialogVisible = ref(false);
const info = reactive({
  id: "",
  imageUrl: "",
  account: "",
  name: "",
  sex: "",
  department: "",
  email: "",
  status: ""
});
const showInfo = row => {
  info.id = row.id;
  info.imageUrl = row.imageUrl;
  info.account = row.account;
  info.name = row.name;
  info.sex = row.sex;
  info.department = row.department;
  info.email = row.email;
  info.status = row.status;
  infoDialogVisible.value = true;
};

const deleteUser = row => {
  ElMessageBox.confirm("确认删除该用户?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deletUser({ id: row.id }).then(async res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        await addOperationLog({operation_person:localStorage.getItem("name"),operation_content:"对id是" + row.id + '的用户删除',operation_level:"高级"});

        togetUser();
        infoDialogVisible.value = false;
        ElMessage.success(res.data.message);
      });
    })
    .catch(() => {});
};

// const currentPage1 = ref(5)
// const currentPage2 = ref(5)
// const currentPage3 = ref(5)
// const currentPage4 = ref(4)
// const pageSize2 = ref(100)
// const pageSize3 = ref(100)
// const pageSize4 = ref(100)
// const small = ref(false)
// const background = ref(false)
// const disabled = ref(false)

const handleSizeChange = val => {
  console.log(`${val} items per page`);
  pageSize.value = val;
  togetUser();
};
const handleCurrentChange = val => {
  console.log(`current page: ${val}`);
  pageNum.value = val;
  togetUser();
};
const identity = ref("产品管理员");
const empowermentDialogVisible = ref(false);
const empowermentOK = () => {
  let data = {
    id: info.id,
    identity: identity.value
  };
  empowerment(data).then(async res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    await addOperationLog({operation_person:localStorage.getItem("name"),operation_content:"对id是" + info.id + '的用户赋权，变成' + identity.value, operation_level:"高级"});
    togetUser();
    empowermentDialogVisible.value = false;
    ElMessage.success(res.data.message);
  });
};
const ruleUserRef =ref();
const userDialogVisible = ref(false);
const ruleUser = reactive({
  id: "",
  account: "",
  password: "",
  name: "",
  sex: "",
  email: "",
  department: ""
});

const userRules = reactive({
  account: [{ required: true, message: "账户", trigger: "blur" }],
  password: [{ required: true, message: "账户", trigger: "blur" }],
  name: [{ required: true, message: "账户", trigger: "blur" }],
  sex: [{ required: true, message: "账户", trigger: "blur" }],
  email: [{ required: true, message: "账户", trigger: "blur" }],
  department: [{ required: true, message: "账户", trigger: "blur" }]
});

const userSubmitForm = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      modifyProductManager(ruleUser).then(async res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        await addOperationLog({operation_person:localStorage.getItem("name"),operation_content:"对id是" + ruleUser.id + '的用户管理员修改',operation_level:"一般"});
        togetUser();
        ElMessage.success(res.data.message);
        userDialogVisible.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const toDeit = () => {
  ruleUser.id = info.id;
  ruleUser.account = info.account;
  ruleUser.name = info.name;
  ruleUser.sex = info.sex;
  ruleUser.email = info.email;
  ruleUser.department = info.department;
  userDialogVisible.value = true;
};

const departmentList = ref([]);
const togetDepartment = () => {
  getDepartment().then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    departmentList.value = res.data.data;
  });
};
//声明周期函数，自动执行初始化
onMounted(() => {
  togetUser();
  togetDepartment();
});
</script>

<style scoped lang="scss">
.productManager {
  .content {
    background: #fff;
    .top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }
  }
}
.breadcrumb {
  display: flex;
  margin-bottom: 10px;
}
</style>